<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right" >
      <el-breadcrumb-item :to="{path: '/admin/notices'}">首页管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path: toPath}">专业管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{deptInfo.college}}</el-breadcrumb-item>
      <el-breadcrumb-item>{{deptInfo.label}}</el-breadcrumb-item>
      <el-breadcrumb-item>教师信息管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card >
      <!--表格区域 stripe 创建带斑马纹的表格-->
      <el-table :data="teacherList" stripe style="font-size: 15px">
        <el-table-column align="center" label="序号" type="index" width="80"></el-table-column>
        <el-table-column align="center" label="工号" prop="id" width="120"></el-table-column>
        <el-table-column align="center" label="姓名" prop="name" width="145"></el-table-column>  
        <el-table-column align="center" label="职称" prop="job" width="140" ></el-table-column>
        <el-table-column align="center" label="电话" prop="phone" width="180" ></el-table-column>
        <el-table-column align="center" label="邮箱" prop="email" width="250" ></el-table-column>
        <el-table-column align="center" label="操作" width="220" > 
          <template slot-scope="scope" >
            <el-button type="success" icon="el-icon-edit" circle @click="editTeacherInfo(scope.row)" ></el-button>
            <el-button type="danger" icon="el-icon-delete" circle @click="deleteTeacher(scope.row.id, scope.row.name)" style="margin-left:10%"></el-button>
          </template>
        </el-table-column>
      </el-table> 
      <el-row v-if="pageParam.currentPage === lastPage">
        <el-link icon="el-icon-plus" type="primary" round style="margin-left: 45%; margin-top: 20px;font-size: 15px" 
          @click="addTeacher">录入教师信息</el-link>
      </el-row>
    </el-card>

    <!-- 底部分页按钮 -->
      <el-pagination background style="margin-left:42%"
        :current-page.sync="pageParam.currentPage"
        :page-size.sync="pageParam.pageSize"
        @current-change="nowPage"
        layout="prev, pager, next"
        :total="total">
      </el-pagination>
    <!--修改课题的对话框-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <!--主体内容区域-->
      <el-form :model="teacherForm" :rules="teacherFormRules" ref="teacherFormRef" label-width="80px" style="margin-left:100px;font-size: 20px">
        <el-form-item prop="id" label="工号">
          <el-input v-model="teacherForm.id" :disabled="!isAdd" placeholder="请输入教师工号"></el-input>
        </el-form-item>
        <el-form-item prop="name" label="姓名">
          <el-input v-model="teacherForm.name" placeholder="请输入教师姓名"></el-input>
        </el-form-item>
        <el-form-item prop="job" label="职称">
          <el-input v-model="teacherForm.job" placeholder="请输入教师职称"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="电话">
          <el-input v-model="teacherForm.phone" placeholder="请输入教师电话"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="teacherForm.email" placeholder="请输入教师邮箱"></el-input>
        </el-form-item>
      </el-form>
        <el-row style="margin-left:30%;margin-top:50px">
          <el-button round @click.native="dialogVisible = false ">取 消</el-button>
          <el-button round v-if="isAdd" type="primary" @click.native="submitTeacherForm('teacherFormRef', 'add')" style="margin-left:10%">完成录入</el-button>
          <el-button round v-else type="success" @click.native="submitTeacherForm('teacherFormRef', 'edit')" style="margin-left:10%">提交修改</el-button> 
        </el-row>
      <!--底部按钮区域--> 
    </el-dialog>
  </div>
</template>

<script>
  import {getDeptById} from '../../axios/dept'
  import {getTeacherPageByDeptId, updateTeacherById, adminAddTeacher, deleteTeacherById, getTeacherTotalByDeptId} from '../../axios/teacher' 
  export default {
    name: 'AdminDeptTeacher',
    data(){
      const phoneValidator = (rule, val, cb) => {
        if (!val) return cb(new Error('请输入手机号'))
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (!regMobile.test(val)) return cb(new Error('请输入合法手机号'))
        cb()
      }
      const emailValidator = (rule, val, cb) => {
        if (!val) return cb(new Error('请输入邮箱'))
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if (!regEmail.test(val)) return cb(new Error('请输入合法邮箱'))
        cb()
      }
      return {
        lastPage: 0, // 最后一页的页码
        total: 0, // 专业总数 
        pageParam:{  currentPage: 1,   pageSize: 10  }, // 页码参数
        isAdd: false, // 对话框此时是否为添加功能
        dialogVisible: false, // 添加/编辑 专业对话框的 显示/隐藏
        dialogTitle: '', // 对话框标题
        toPath: '', // 面包屑导航栏跳转地址 
        deptInfo: { }, // 专业信息
        teacherList: [], // 教师列表
        teacherForm: { }, // 编辑/添加教师表格数据
        teacherFormRules:{
          id: [ { required: true, message: '教师工号不能为空', trigger: 'blur' } ],
          name: [ { required: true, message: '教师姓名不能为空', trigger: 'blur' } ],
          job: [ { required: true, message: '教师职称不能为空', trigger: 'blur' } ],
          phone: [ {required: true,validator: phoneValidator, trigger: 'blur'} ],
          email: [ {required: true, validator: emailValidator, trigger: 'blur'} ]
        }
      }
    },
    watch:{ 
    },
    created(){ 
      let paths = this.$route.path.split('/')  
      this.toPath = '/' + paths[1] + '/' + paths[2] + '/' + paths[4] 
      this.getDeptInfo(this.$route.params.id)
      this.getTeacherList(this.$route.params.id)
    },
    methods:{
      // 页码改变时，及时更新数据
      nowPage(page){
        this.pageParam.currentPage = page // 更新当前指向的页码
        this.getTeacherList(this.$route.params.id)
      }, 
      getDeptInfo(id){
        // 向后端发送请求，获取指定 id 的专业信息 
        getDeptById(id).then(res => {
          if(res.success){
            this.deptInfo = res.data  
          } 
        }) 
        // 无后端模拟数据
        // this.deptInfo = { id: id, label: '计算机科学与技术', collegeId: '014301', college: '数学与计算机学院' }
        // this.label = this.deptInfo.label
        // this.college = this.deptInfo.college 
      },
      // 获取指定专业的 所有教师信息列表
      getTeacherList(id){
        // 向后端发送请求，获取指定专业 id 的教师列表
        getTeacherPageByDeptId(id, this.pageParam).then(res => {
          if(res.success){
            this.teacherList = res.data 
          } 
        }) 
        getTeacherTotalByDeptId(id).then(res => {
          if(res.success){
            this.total = res.data 
            this.lastPage = Math.floor(this.total / 10);
            if(this.total % 10 !== 0) this.lastPage ++
          } 
        })
        // 无后端模拟数据
        // this.teacherList = [
        //   {id: '610911', name: '罗翔', job: '教授', phone: '13909098080', email: 'luoxiangxf@163.com'},
        //   {id: '610912', name: '张三', job: '副教授', phone: '13909098081', email: 'zhangsan@163.com'},
        //   {id: '610913', name: '李四', job: '教授', phone: '13909098082', email: 'lisi@163.com'},
        //   {id: '610914', name: '王五', job: '讲师', phone: '13909098021', email: 'wangwu@163.com'},
        //   {id: '610915', name: '赵六', job: '副教授', phone: '13909098022', email: 'zhaoliu@163.com'}
        // ]
      },
      // 编辑教师信息
      editTeacherInfo(teacherInfo){
        this.isAdd = false
        this.dialogTitle = '编辑教师信息'
        this.teacherForm = teacherInfo
        this.dialogVisible = true   
      },
      addTeacher(){
        this.isAdd = true
        this.dialogTitle = '录入教师信息'
        this.teacherForm = {}
        this.dialogVisible = true   
      }, 
      deleteTeacher(id, name){
        this.$confirm('此操作将永久删除“' + name + '(' + id +') ”教师, 是否继续?', '提示', {
          roundButton: true,
          confirmButtonText: '删除',
          cancelButtonText: '取消', 
          type: 'warning'
        }).then(() => {
          // 发送后端请求，删除指定 id 的通知
          deleteTeacherById(id).then(res => {
            if(res.success){
              this.$message.success('删除成功!'); 
              this.getTeacherList(this.$route.params.id)
            }
          }) 
        }).catch(() => {
          this.$message.info('已取消删除!');          
        }); 
      },
      submitTeacherForm(teacherForRef, todo){  
        this.$refs[teacherForRef].validate(valid =>{ 
          if(valid){ 
            this.$confirm('确认提交吗?', '系统提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then( () => {
              if(todo === 'edit'){
                // 此时发送后端请求，保存修改信息
                updateTeacherById(this.teacherForm).then(res => {
                  if(res.success){
                    this.$message.success('修改成功!')
                    this.dialogVisible = false 
                    this.getTeacherList(this.$route.params.id)
                  } 
                }) 
              }else{  
                this.teacherForm.collegeId = this.deptInfo.collegeId
                this.teacherForm.deptId = this.deptInfo.id
                // 此时发送后端请求，保存录入信息
                adminAddTeacher(this.teacherForm).then(res => {
                  if(res.success){
                    this.$message.success('录入成功!')
                    this.dialogVisible = false 
                    this.getTeacherList(this.$route.params.id)
                  }  
                })   
              }  
            }).catch(() => {  
              this.$message.info('已取消提交!');   
            })
          }else{
            this.$message.error('请按要求填写各项信息!')
          }
        })
      }
    }
  }
</script>

<style scoped>
  .el-form-item .el-input{
    width: 57%;
  }
</style>